import { copy } from "clipboard";
import { useUserStore } from "@/stores/useUserStore";
import { storeToRefs } from "pinia";
import { toPng } from "html-to-image";
import { reactive } from "vue";

export default function () {
  const userStore = useUserStore();
  const { userInfo } = storeToRefs(userStore);

  const shareConfig = reactive({
    img: "",
    link: "",
  });

  /**
   * 复制 主页 链接到剪切板
   */
  function copyToClipboard() {
    const text = `${location.href}pages/friend/friend?id=${userInfo.value?.id}`;

    try {
      copy(text);
      uni.showToast({
        title: "复制成功，快去粘贴分享吧！",
        icon: "success",
        duration: 2000,
      });
      shareConfig.link = text;
    } catch (e) {
      uni.showToast({
        title: `Copy to clipboard failed, ${e}`,
        icon: "fail",
        duration: 2000,
      });
    }
  }

  function handleShare(el: HTMLElement) {
    toPng(el)
      .then(function (dataUrl) {
        shareConfig.img = dataUrl;
        copyToClipboard();
        // const img = new Image();
        // img.src = dataUrl;
        // document.body.appendChild(img);
      })
      .catch(function (error) {
        console.error("oops, something went wrong!", error);
      });
  }

  return {
    handleShare,
    shareConfig,
  };
}
